"""
用户相关的API接口封装
"""
import json
from typing import Dict, List, Optional, Any
from utils.api_helper import GLMAPIClient
from config.config import APIConfig


class UserAPI:
    """用户API接口类"""
    
    def __init__(self, api_key: str = None):
        """
        初始化用户API
        
        Args:
            api_key: API密钥，如果为None则从配置获取
        """
        if api_key is None:
            api_key = APIConfig.get_api_key()
        
        config = APIConfig.get_config()
        self.client = GLMAPIClient(
            api_key=api_key,
            base_url=config.get("base_url"),
            timeout=config.get("timeout", 60)
        )
    
    def simple_chat(self, user_prompt: str, system_prompt: Optional[str] = None) -> str:
        """
        简单聊天接口
        
        Args:
            user_prompt: 用户提示
            system_prompt: 系统提示，可选
            
        Returns:
            模型回复内容
        """
        return self.client.simple_chat(user_prompt, system_prompt)
    
    def chat_completion(
        self, 
        messages: List[Dict[str, str]], 
        model: str = "glm-4.6",
        temperature: float = 1.0,
        max_tokens: int = 1000,
        stream: bool = False
    ) -> Dict[str, Any]:
        """
        聊天完成接口
        
        Args:
            messages: 消息列表
            model: 模型名称
            temperature: 温度参数
            max_tokens: 最大令牌数
            stream: 是否流式响应
            
        Returns:
            API响应数据
        """
        return self.client.chat_completion(
            messages=messages,
            model=model,
            temperature=temperature,
            max_tokens=max_tokens,
            stream=stream
        )
    
    def test_chat_functionality(self, test_case_name: str) -> Dict[str, Any]:
        """
        测试聊天功能
        
        Args:
            test_case_name: 测试用例名称
            
        Returns:
            测试结果
        """
        test_cases = APIConfig.TEST_CASES
        
        if test_case_name not in test_cases:
            return {
                "success": False,
                "error": f"测试用例 '{test_case_name}' 不存在"
            }
        
        test_case = test_cases[test_case_name]
        
        try:
            response = self.simple_chat(
                user_prompt=test_case["user_prompt"],
                system_prompt=test_case["system_prompt"]
            )
            
            # 验证响应
            if not response or response == "无法获取回复":
                return {
                    "success": False,
                    "error": "API响应为空或失败"
                }
            
            # 验证关键词
            missing_keywords = []
            for keyword in test_case["expected_keywords"]:
                if keyword not in response:
                    missing_keywords.append(keyword)
            
            return {
                "success": len(missing_keywords) == 0,
                "response": response,
                "missing_keywords": missing_keywords,
                "test_case": test_case_name
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }